import { useState } from 'react';
import { useMount } from 'ahooks';

export interface RequestCallback {}

export interface RequestOptions {
  params?: any;
  onSuccess?: (data: any) => any;
  onError?: (err: any) => any;
  lazy?: boolean;
  isRun?: boolean;
}

export interface RequestResponse {
  loading: boolean;
  run: (params?: any) => void;
  data: any;
}

export default (
  service: (params: any) => Promise<any>,
  options?: RequestOptions,
): RequestResponse => {
  const isRun = options?.isRun ?? true;
  const [loading, setLoading] = useState<boolean>(true);
  const [state, setState] = useState<any>();
  const run = (params?: any) => {
    let data: any = undefined;
    if (options?.params) {
      if (typeof options.params === 'object') {
        data = { ...options.params };
      } else {
        data = options.params;
      }
    }

    if (params) {
      if (typeof params === 'object') {
        data = { ...data, ...params };
      } else {
        data = params;
      }
    }
    console.log('params', data);

    setLoading(true);
    service(data)
      .finally(() => {
        setLoading(false);
      })
      .then(result => {
        if (result.status) {
          setState(result);
          options?.onSuccess && options.onSuccess(result);
        } else if (options?.onError) {
          options?.onError && options.onError(result);
        }
      });
  };
  useMount(() => {
    if (!options?.lazy && isRun) {
      run();
    } else {
      setLoading(false);
    }
  });

  return {
    loading,
    run,
    data: state,
  };
};
